import { PageContainer } from "@ant-design/pro-components";
import { Button, Card, Form, InputNumber, Switch } from "antd";
import { connect } from "umi";
import { namespace } from "./configFile";
import { useEffect, useState } from "react";
import styles from "./styles.less";

const Page = (props) => {
  const { dispatch, data, submitLoading } = props;
  const [form] = Form.useForm();
  const [formData, setFormData] = useState([]);

  useEffect(() => {
    dispatch({
      type: `${namespace}/pageInit`,
    });
  }, []);
  const handleChange = (val, key, params) => {
    let newFormData = [...formData];
    let { id } = params;
    let index = newFormData.findIndex((f) => f.id == id);
    if (index >= 0) {
      newFormData[index][key] = val;
    } else {
      let newParams = { ...params };
      newParams[key] = val;
      newFormData.push(newParams);
    }
    setFormData(newFormData);
    console.log(val, formData, params);
  };

  const handleSubmit = async (params) => {
    console.log(formData);
    dispatch({
      type: `${namespace}/toggleState`,
      params: formData,
      callback: () => {
        dispatch({ type: `${namespace}/pageInit` });
      },
    });
  };

  return (
    <PageContainer className={styles.businessRemind}>
      <Card>
        <div className={styles.item}>
          <div className={styles.itemOne}>提醒项</div>
          <div className={styles.itemTow}>是否开启</div>
          <div className={styles.itemThree}>商家端初始值</div>
        </div>

        <Form form={form}>
          {data.map((v, k) => (
            <div className={styles.item} key={k}>
              <div className={styles.itemOne}>{v.name}</div>
              <div className={styles.itemTow}>
                <Switch
                  defaultChecked={v.openFlag == 1}
                  onChange={(val) => {
                    handleChange(val ? "1" : "0", "openFlag", v);
                  }}
                />
              </div>
              <div className={styles.itemThree}>
                <InputNumber
                  defaultValue={v.value}
                  style={{ width: "100%" }}
                  placeholder="请输入0-100的数字"
                  onChange={(val) => {
                    handleChange(val, "value", v);
                  }}
                  min={0}
                  max={100}
                />
              </div>
            </div>
          ))}
        </Form>
        <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
          确认保存
        </Button>
      </Card>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/toggleState`],
}))(Page);
